import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { addTodo } from "../store/todos.slice";

function TodoHeader() {
  const [title, setTitle] = useState("");
  const dispatch = useDispatch();
  const addTodoHandler = (event) => {
    // 如果用户不是敲击回车键
    if (event.key !== "Enter") return;
    // title没值没输入
    if (!title) return;
    // 传递payload参数
    dispatch(addTodo({ title }));
    setTitle("");
  };
  return (
    <header className='header'>
      <h1>todos</h1>
      <input
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        onKeyUp={addTodoHandler}
        className='new-todo'
        placeholder='What needs to be done?'
        autoFocus
      />
    </header>
  );
}
export default TodoHeader;
